import { Injectable, CanActivate, ExecutionContext, UnauthorizedException } from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { EntityManager, In } from 'typeorm';
import { Permission } from '../../entities/permission.entity';
import { InjectEntityManager } from '@nestjs/typeorm';
@Injectable()
export class RoleGuard implements CanActivate {
    constructor(
      @InjectEntityManager()
      private readonly entityManager: EntityManager,
      private reflector: Reflector
    ) {}
    async canActivate(context: ExecutionContext): Promise<boolean> {
      const requirePermissions = this.reflector.getAllAndOverride<string[]>('roles', [
          context.getClass(),
          context.getHandler()
      ]);
      if (!requirePermissions) {
          return true;
      }
      const request = context.switchToHttp().getRequest()
      const user = request.user
      if (!user) {
          return true
      }
      const roles: any[] = await this.entityManager.find('Role', {
          where: {
            id: In(request.user.roles.map((item) => item.id))
          },
          relations: ['permissions']
      });
      const permissions: Permission[] = roles.reduce((total, current) => {
          total.push(...current.permissions)
          return total
      }, [])
      let hasPermission:any = true
      hasPermission = permissions.find((item) => requirePermissions.includes(item.code))
      // console.log(hasPermission, requirePermissions, requirePermissions, 'permissions')
      if (!hasPermission) {
          throw new UnauthorizedException('您没有访问该接口的权限')
      }
      return hasPermission
    }
}